package Exam.model;

import Exam.pojo.User;
import Exam.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;



public class LoginModel {

    public User login(String username, String password) {
        try {
            User user = new User();
            Connection conn = JDBCUtil.getConn();
            String sql = "SELECT * FROM user " +
                    "WHERE username = ? AND pwd = ?";
            PreparedStatement statement
                    = conn.prepareStatement(sql);
            statement.setString(1, username);
            statement.setString(2, password);
            ResultSet rs = statement.executeQuery();
            rs.next();
            setUserParam(user, rs);

            rs.close();
            statement.close();
            return user;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    private void setUserParam(User user, ResultSet rs) throws SQLException {

        String username =rs.getString("username");
        String nickname = rs.getString("nickname");
        user.setUsername(username)
                .setNickname(nickname)
                .setPassword("");
    }


    public boolean canLogin(String username, String pwd) {
        Connection conn = JDBCUtil.getConn();
        String sql = "SELECT count(*) FROM user WHERE " +
                "username = ? AND pwd = ?";
        try {
            PreparedStatement statement
                    = conn.prepareStatement(sql);
            statement.setString(1, username);
            statement.setString(2, pwd);
            ResultSet rs = statement.executeQuery();
            boolean canLogin = false;
            if (rs.next()) {
                int count = rs.getInt(1);
                canLogin = count > 0;
            }
            statement.close();
            rs.close();
            return canLogin;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
